package cn.livingCloud.controller.user;

import cn.livingCloud.dto.UserFormDto;
import cn.livingCloud.dto.UserListDto;
import cn.livingCloud.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.validation.Valid;

/**
 * Created by 唐旭 on 2015/12/2.
 */
@Controller
@RequestMapping("/admin/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/list.htm")
    public String list(UserListDto listDto, Model model) {
        userService.getUserList(listDto);
        model.addAttribute("listDto", listDto);
        return "user/list";
    }

    @RequestMapping("/edit.htm")
    public String show(String uuid, Model model) {
        UserFormDto formDto = userService.loadUserFormDto(uuid);
        model.addAttribute("formDto", formDto);
        return "user/edit";
    }


    @RequestMapping(value = "/edit.htm", method = RequestMethod.POST)
    public String edit(@ModelAttribute("formDto") @Valid UserFormDto formDto, BindingResult result, Model model) {
        if (result.hasErrors()) {
            return "user/edit";
        }
        userService.editUser(formDto);
        return "redirect:list.htm?edit=success";
    }
}
